package com.cql.framework.task;

import com.cql.common.constant.RedisConstants;
import com.cql.common.core.DO.MomentDO;
import com.cql.common.core.DTO.MomentInfoDTO;
import com.cql.common.core.redis.RedisCache;
import com.cql.mapper.MomentMapper;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Collection;

/**
 * @author cql
 */
public class InsertMomentViewJob extends QuartzJobBean {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MomentMapper momentMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * TODO 简单定时任务用于从redis中更新moment到数据库
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Collection<String> keys = redisCache.keys(RedisConstants.MOMENT.substring(0, RedisConstants.MOMENT.length() - 5) + "*");
        keys.forEach(key -> {
            logger.info("更新 {} ", key);
            MomentInfoDTO momentInfoDTO = redisCache.getCacheObject(key);
            MomentDO moment = new MomentDO();
            moment.setMomentId(momentInfoDTO.getMomentId());
            moment.setView(momentInfoDTO.getViewNum());
            momentMapper.updateById(moment);
            /**
             * 在文章修改功能修改文章时，直接删除缓存中的文章，当然，删之前要更新数据库
             */
        });
    }
}
